import { useState, useEffect } from 'react'
import { Row, Col, Table, Alert, message, Modal, Space, TablePaginationConfig, TableColumnType } from 'antd';
import { VideoCameraOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import moment, { Moment } from 'moment'
import style from './index.module.less'
import { CaseSchema } from '@src/components/schema/caseSchema'
import { VideoCourtSchema, VideoDownloadSchema, VideoPartySchema } from '@src/components/schema/videoCourt'
import { awaitWrap, confirmAction } from '@src/assets/js/tool';
import SignFiles from './components/signFiles'
import OperateBtns from './components/operateBtns'
import FileList from './components/fileList'
import { getMeetingDataRequest, getCaseDataRequest, getPersonRequest, delRequest } from './ajax'
import { PartySchema } from '@src/components/schema/caseSchema';
import PersonModal from './components/personModal'
import UploadModal from './components/uploadModal'


function getColumns (
  d: VideoCourtSchema | { [k: string]: any },
  refreshFn: () => void
): Array<TableColumnType<VideoPartySchema>> {
  return [
    {
      title: '序号',
      dataIndex: 'order',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '仲裁地位',
      dataIndex: 'type',
      key: 'type'
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      key: 'mobile'
    },
    {
      title: '认证情况',
      dataIndex: 'certifyid',
      key: 'certifyid',
      render: (v: boolean) => {
        return v ? '已认证' : '未认证'
      }
    },
    {
      title: '是否已签名',
      dataIndex: 'signed_fileid',
      key: 'signed_fileid',
      render: (v: boolean) => {
        return v ? '已签名' : ''
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status'
    },
    {
      title: '操作',
      dataIndex: 'index',
      key: 'operate',
      render: (value: number, line: VideoPartySchema) => {
        if (!d.id || ['预约', '变更'].indexOf(d.status) === -1 || line.type === '仲裁秘书') {
          return null
        }
        return (
          <span className={style['operate-cell']}>
            <span onClick={() => confirmAction('您确定要删除该参会人员吗？', () => { delPersonHandle(line.id, refreshFn) })}>删除</span>
          </span>
        )
      }
    }
  ]
}

async function delPersonHandle (id: string, refreshFn: () => void) {
  const hide = message.loading('删除中', 120)
  const [e] = await awaitWrap(delRequest(id))
  hide()
  if (e === null) {
    refreshFn()
  }
}

async function initPerson (id: string, setList: (v: VideoPartySchema[]) => void, setLoading: (v: boolean) => void) {
  setLoading(true)
  const [e, d] = await awaitWrap(getPersonRequest(id))
  setLoading(false)
  if (e === null && d !== null) {
    d.forEach((li, i) => {
      li.order = i + 1
    })
    setList(d)
  }
}

async function initMeetingData (id: string, setMeetingData: (v: VideoCourtSchema) => void) {
  const [e, d] = await awaitWrap(getMeetingDataRequest(id))
  if (e === null && d !== null) {
    setMeetingData(d)
  }
}

async function initCaseData (id: string, setCaseData: (v: CaseSchema) => void ) {
  const [e, d] = await awaitWrap(getCaseDataRequest(id))
  if (e === null && d !== null) {
    setCaseData(d)
  }
}

async function initData (
  {id, caseid }: { id: string, caseid: string },
  setMeetingData: (v: VideoCourtSchema) => void,
  setCaseData: (v: CaseSchema) => void,
  setList: (v: VideoPartySchema[]) => void,
  setLoading: (v: boolean) => void
) {
  const hide = message.loading('加载中', 120)
  Promise.all([initMeetingData(id, setMeetingData), initCaseData(caseid, setCaseData), initPerson(id, setList, setLoading)])
    .then(() => {
      hide()
    })
    .catch(() => {
      hide()
    })
}

// 获取时间区间
 function getTimeRange (start: number, end: number) {
  if (!start && !end) {
    return '未开始'
  }
  let year = ''
  let s: Moment = moment()
  let e: Moment = moment()
  if (start) {
    s = moment(start * 1000)
    year = s.format('YYYY-MM-DD')
  }
  if (start && end) {
    e = moment(end * 1000)
    return `${year} ${s.format('HH:mm')}~${e.format('HH:mm')}`
  }
  if (end) {
    return ''
  }
  return `${year} ${s.format('HH:mm')}`
}

async function tableChange (o: TablePaginationConfig) {

}

function renderParty (name: string, list: PartySchema[]) {
  if (name) {
    return name
  }
  if (list instanceof Array && list.length > 0) {
    return list.map(li => li.name).join()
  }
  return '无'
}

interface Props {
  meta: { id: string, caseid: string }
}

function Main ({ meta }: Props) {
  const [caseData, setCaseData] = useState<{ [k: string]: any } | CaseSchema>({})
  const [meetingData, setMeetingData] = useState<{ [k: string]: any } | VideoCourtSchema>({})
  const [loading, setLoading] = useState(false)
  const [list, setList] = useState<VideoPartySchema[]>([])
  const [visible, setVisible] = useState(false)
  const [modifyData, setModifyData] = useState<VideoPartySchema | null>(null)
  const [uploadVisible, setUploadVisible] = useState(false)
  const columns = getColumns(meetingData, () => { initData(meta, setMeetingData, setCaseData, setList, setLoading) })
  useEffect(() => {
    initData(meta, setMeetingData, setCaseData, setList, setLoading)
  }, [meta])
  return (
    <div className={style.container}>
      <PersonModal
        visible={visible}
        hearingroomid={meetingData.hearingroomid}
        meetingid={meetingData.id}
        meetingData={meetingData as VideoCourtSchema}
        caseData={caseData as CaseSchema}
        data={modifyData}
        hide={() => { setVisible(false); setModifyData(null) }}
        refreshFn={() => initData(meta, setMeetingData, setCaseData, setList, setLoading)}
      />
      <UploadModal visible={uploadVisible} meetingid={meetingData.id} refreshFn={() => initData(meta, setMeetingData, setCaseData, setList, setLoading)} hide={() => setUploadVisible(false)} />
      {/* <InfoModal visible={this.state.infoVisible} data={this.state.meetingData} hide={() => this.setState({ infoVisible: false })} /> */}
      <div className={style.header}>
        <div className={style.title}>
          <div className={style['title-icon']}>
            <VideoCameraOutlined />
          </div>
          <div className={style['title-text']}>
            <span>{caseData.caseno_desc}</span>
            {meetingData.type && <span>（{meetingData.type}）</span>}
          </div>
        </div>
      </div>
      <div className={style['basic-info']}>
        <Row>
          <Col span={8}>
            <div className={style['basic-cell']}>
              <div className={style['basic-cell-label']}>申请人：</div>
              <div className={style['basic-cell-text']}>{renderParty(caseData.applicant_name, caseData.applicants)}</div>
            </div>
          </Col>
          <Col span={8}>
            <div className={style['basic-cell']}>
              <div className={style['basic-cell-label']}>被申请人：</div>
              <div className={style['basic-cell-text']}>{renderParty(caseData.respondent_name, caseData.respondents)}</div>
            </div>
          </Col>
          <Col span={8}>
            <div className={style['basic-cell']}>
              <div className={style['basic-cell-label']}>案件状态：</div>
              <div className={style['basic-cell-text']}>{caseData.status || '无'}</div>
            </div>
          </Col>
          <Col span={8}>
            <div className={style['basic-cell']}>
              <div className={style['basic-cell-label']}>案件程序：</div>
              <div className={style['basic-cell-text']}>{caseData.procedure || '无'}</div>
            </div>
          </Col>
          <Col span={8}>
            <div className={style['basic-cell']}>
              <div className={style['basic-cell-label']}>办案秘书：</div>
              <div className={style['basic-cell-text']}>{caseData.processer || '无'}</div>
            </div>
          </Col>
          <Col span={8}>
            <div className={style['basic-cell']}>
              <div className={style['basic-cell-label']}>速录员：</div>
              <div className={style['basic-cell-text']}>{meetingData.recorder || '无'}</div>
            </div>
          </Col>
          <Col span={8}>
            <div className={style['basic-cell']}>
              <div className={style['basic-cell-label']}>约庭用途：</div>
              <div className={style['basic-cell-text']}>{meetingData.use || '无'}</div>
            </div>
          </Col>
          <Col span={8}>
            <div className={style['basic-cell']}>
              <div className={style['basic-cell-label']}>开庭时间：</div>
              <div className={style['basic-cell-text']}>{getTimeRange(meetingData.begin_datetime, meetingData.end_datetime)}</div>
            </div>
          </Col>
          <Col span={8}>
            <div className={style['basic-cell']}>
              <div className={style['basic-cell-label']}>实际时间：</div>
              <div className={style['basic-cell-text']}>{getTimeRange(meetingData.meeting_begin_datetime, meetingData.meeting_end_datetime)}</div>
            </div>
          </Col>
          <Col span={8}>
            <div className={style['basic-cell']}>
              <div className={style['basic-cell-label']}>开庭状态：</div>
              <div className={style['basic-cell-text']}>{meetingData.status}</div>
            </div>
          </Col>
          <SignFiles list={meetingData.signed_file instanceof Array ? meetingData.signed_file : []} />
          {
            ['会议结束', '完成'].includes(meetingData.status) && (
              <Col span={24}>
                <Alert message={(
                  <div>
                    <div>1. 视频庭审下载需要使用秘书华为云账号（DL+手机号）和密码，登陆华为云视频下载界面，选择【高清视频下载】， 并根据指引下载到本地计算机；</div>
                    <div>2. 视频庭审录制材料开庭后三个月将无法下载，请即时下载，并确认视频内容无误后，进行刻录归档；</div>
                    <div>3. 请将【已签名文件】最终版本下载后与视频庭审录制材料一并刻录归档；确认以上数据归档后，请点击【完成会议】。</div>
                  </div>
                )} type='warning' closable showIcon />
              </Col>
            )
          }
        </Row>
      </div>

      <div className={style['btn-line']}>
        <Space>
          <OperateBtns meetingData={meetingData} addHandle={() => { setVisible(true); setModifyData(null) }} refreshFn={() => initData(meta, setMeetingData, setCaseData, setList, setLoading)} showUpload={() => setUploadVisible(true)} />
          <FileList meetingData={meetingData} />
        </Space>
      </div>

      <div className={style['table-container']}>
        <Table loading={loading} rowKey='id' columns={columns} dataSource={list} pagination={false} onChange={v => tableChange(v)} />
      </div>
    </div>
  )
}

export default Main
